using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using umbraco.cms.businesslogic.member;
using Umbraco.Ecommerce.BusinessLogic;

namespace Umbraco.Ecommerce.WebShop.UserControls
{
    public partial class CheckOut : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Validate cart has items.
            if (Library.GetCart.Items.Length == 0)
                Response.Redirect(umbraco.library.NiceUrl(umbraco.presentation.nodeFactory.Node.GetCurrent().Id));

            thankyou.Visible = false;
            BackToBasket.CausesValidation = false;

            if (!IsPostBack)
            {
                if (umbraco.library.GetDictionaryItem("description") != "")
                    lttDescription.Text = umbraco.library.GetDictionaryItem("description");
                //set Quantity label          
                if (umbraco.library.GetDictionaryItem("quantity") != "")
                    lttHeadQuantity.Text = umbraco.library.GetDictionaryItem("quantity");
                //set Total label
                if (umbraco.library.GetDictionaryItem("total") != "")
                    lttHeadTotal.Text = umbraco.library.GetDictionaryItem("total");
                lttTotal2.Text = umbraco.library.GetDictionaryItem("total");
                //set subTotal label
                if (umbraco.library.GetDictionaryItem("subtotal") != "")
                    lttSubtotal2.Text = umbraco.library.GetDictionaryItem("subtotal");
                //set Shipping label
                if (umbraco.library.GetDictionaryItem("shipping") != "")
                    lttShipping2.Text = umbraco.library.GetDictionaryItem("shipping");
                //Set company label
                if (umbraco.library.GetDictionaryItem("company") != "")
                {
                    lttInvCompany.Text = umbraco.library.GetDictionaryItem("company");
                    lttDelCompany.Text = umbraco.library.GetDictionaryItem("company");
                }
                //Set firstname label
                if (umbraco.library.GetDictionaryItem("firstname") != "")
                {
                    lttInvFirstname.Text = umbraco.library.GetDictionaryItem("firstname");
                    lttDelFirstname.Text = umbraco.library.GetDictionaryItem("firstname");
                }
                //Set lastname label
                if (umbraco.library.GetDictionaryItem("lastname") != "")
                {
                    lttInvLastname.Text = umbraco.library.GetDictionaryItem("lastname");
                    lttDelLastname.Text = umbraco.library.GetDictionaryItem("lastname");
                }

                //Set street label
                if (umbraco.library.GetDictionaryItem("street") != "")
                {
                    lttInvStreet.Text = umbraco.library.GetDictionaryItem("street");
                    lttDelStreet.Text = umbraco.library.GetDictionaryItem("street");
                }
                //Set postalcode label
                if (umbraco.library.GetDictionaryItem("postalcode") != "")
                {
                    lttInvPost.Text = umbraco.library.GetDictionaryItem("postalcode");
                    lttDelPost.Text = umbraco.library.GetDictionaryItem("postalcode");
                }
                //Set city label
                if (umbraco.library.GetDictionaryItem("city") != "")
                {
                    lttInvCity.Text = umbraco.library.GetDictionaryItem("city");
                    lttDelCity.Text = umbraco.library.GetDictionaryItem("city");
                }
                //Set country label
                if (umbraco.library.GetDictionaryItem("country") != "")
                {
                    lttInvCountry.Text = umbraco.library.GetDictionaryItem("country");
                    lttDelCountry.Text = umbraco.library.GetDictionaryItem("country");
                }
                //Set telephone label
                if (umbraco.library.GetDictionaryItem("telephone") != "")
                    lttInvPhone.Text = umbraco.library.GetDictionaryItem("telephone");
                //Set email label
                if (umbraco.library.GetDictionaryItem("email") != "")
                    lttInvEmail.Text = umbraco.library.GetDictionaryItem("email");


                //Set NO
                if (umbraco.library.GetDictionaryItem("no") != "")
                    rblDeliveryadress.Items.FindByText("No").Text = umbraco.library.GetDictionaryItem("no");

                //Set YES
                if (umbraco.library.GetDictionaryItem("yes") != "")
                    rblDeliveryadress.Items.FindByText("Yes").Text = umbraco.library.GetDictionaryItem("yes");


                //Set next button
                if (umbraco.library.GetDictionaryItem("next") != "")
                    toOrderConfirmation.Text = umbraco.library.GetDictionaryItem("next");
                //Set previous button
                if (umbraco.library.GetDictionaryItem("previous") != "")
                {
                    BackToBasket.Text = umbraco.library.GetDictionaryItem("previous");
                    editDeliveryInfo.Text = umbraco.library.GetDictionaryItem("previous");
                }

                //Set invoice information
                if (umbraco.library.GetDictionaryItem("invoiceinformation") != "")
                {
                    legendInvoiceInfo.InnerHtml = umbraco.library.GetDictionaryItem("invoiceinformation");
                    legendInvoiceInformation.InnerHtml = umbraco.library.GetDictionaryItem("invoiceinformation");
                }
                //Set Delivery adress
                if (umbraco.library.GetDictionaryItem("deliveryadress") != "")
                {
                    legendDeliveryAdress.InnerHtml = umbraco.library.GetDictionaryItem("deliveryadress");
                    legendDeliveryInformation.InnerHtml = umbraco.library.GetDictionaryItem("deliveryadress");
                }
                //Set other delivery adress
                if (umbraco.library.GetDictionaryItem("otherdelivery") != "")
                    legendOtherDelivery.InnerHtml = umbraco.library.GetDictionaryItem("otherdelivery");
                //Set payment method
                if (umbraco.library.GetDictionaryItem("paymentmethod") != "")
                    legendPaymentMethod.InnerHtml = umbraco.library.GetDictionaryItem("paymentmethod");
                //Set Order summary
                if (umbraco.library.GetDictionaryItem("ordersummary") != "")
                    legendOrderSumary.InnerHtml = umbraco.library.GetDictionaryItem("ordersummary");


                confirmationholder.Visible = false;
                BindData();
                PrefillData();

            }
        }

        private void PrefillData()
        {
            /* If user previously typed info - prefill for*/
            try
            {
                txtInvCompany.Text = Session["company"].ToString();
                txtInvFirstname.Text = Session["firstname"].ToString();
                txtInvLastname.Text = Session["lastname"].ToString();
                txtInvEmail.Text = Session["email"].ToString();
                txtInvStreet.Text = Session["streetname"].ToString();
                txtInvPost.Text = Session["postalcode"].ToString();
                txtInvCity.Text = Session["city"].ToString();
                txtInvPhone.Text = Session["telephone"].ToString();

            }
            catch { }
        }

        private void SetPrefillData()
        {
            Session["company"] = txtInvCompany.Text;
            Session["firstname"] = txtInvFirstname.Text;
            Session["lastname"] = txtInvLastname.Text;
            Session["email"] = txtInvEmail.Text;
            Session["streetname"] = txtInvStreet.Text;
            Session["postalcode"] = txtInvPost.Text;
            Session["city"] = txtInvCity.Text;
            Session["telephone"] = txtInvPhone.Text;

        }
        private void BindData()
        {
            if (Library.GetCart.Items.Length > 0)
            {
                cartItemRepeater.DataSource = Library.GetCart.Items;
                cartItemRepeater.DataBind();

                lttSubTotal.Text = Library.FormattedPrice(Library.GetCart.TotalSum);
                lttShipping.Text = Library.FormattedPrice(Store.GetDeliveryCostByCountry(Store.GetDeliveryCountry));
                lttTotal.Text = Library.FormattedPrice(Store.GetDeliveryCostByCountry(Store.GetDeliveryCountry) + Library.GetCart.TotalSum);


            }
        }

        protected void cartItemRepeater_ItemDataBound(object source, RepeaterItemEventArgs e)
        {
            CartItem ci = (CartItem)e.Item.DataItem;
            Literal lttProductName = (Literal)e.Item.FindControl("lttProductName");
            Literal lttQuantity = (Literal)e.Item.FindControl("lttQuantity");
            Literal lttItemTotal = (Literal)e.Item.FindControl("lttItemTotal");

            lttProductName.Text = ci.ProductName;
            lttQuantity.Text = ci.Quantity.ToString();
            lttItemTotal.Text = Library.FormattedPrice(ci.Quantity * ci.Price);
        }

        protected void BackToBasket_Click(object sender, EventArgs e)
        {
            SetPrefillData();
            Response.Redirect(umbraco.library.NiceUrl(umbraco.presentation.nodeFactory.Node.GetCurrent().Id) + "/Cart");
        }

        protected void toOrderConfirmation_Click(object sender, EventArgs e)
        {
            this.Page.Validate();
            if (this.Page.IsValid)
            {
                diholder.Visible = false;
                confirmationholder.Visible = true;

                SetPrefillData();

                //invoice data
                lttCompany.Text = txtInvCompany.Text;
                lttFirstname.Text = txtInvFirstname.Text;
                lttLastname.Text = txtInvLastname.Text;
                lttEmail.Text = txtInvEmail.Text;
                lttStreetname.Text = txtInvStreet.Text;
                lttPostalcode.Text = txtInvPost.Text;
                lttCity.Text = txtInvCity.Text;
                lttCountry.Text = ddlInvCountry.SelectedValue;
                lttTelephone.Text = txtInvPhone.Text;

                //show delivery data
                if (rblDeliveryadress.SelectedIndex == 0)
                {
                    lttSumDelCompany.Text = txtDelCompany.Text;
                    lttSumDelFirstname.Text = txtDelFirstname.Text;
                    lttSumDelLastname.Text = txtDelLastname.Text;
                    lttSumDelStreet.Text = txtDelStreet.Text;
                    lttSumDelPostalcode.Text = txtDelPost.Text;
                    lttSumDelCity.Text = txtDelCity.Text;
                    lttSumDelCountry.Text = ddlDelCountry.SelectedValue;
                }
                else
                {
                    lttSumDelCompany.Text = txtInvCompany.Text;
                    lttSumDelFirstname.Text = txtInvFirstname.Text;
                    lttSumDelLastname.Text = txtInvLastname.Text;
                    lttSumDelStreet.Text = txtInvStreet.Text;
                    lttSumDelPostalcode.Text = txtInvPost.Text;
                    lttSumDelCity.Text = txtInvCity.Text;
                    lttSumDelCountry.Text = ddlInvCountry.SelectedValue;
                }


                if (rdbPayment.SelectedIndex == 0)
                {
                    confirmorder.Text = "Go to secure payment >>";
                }
                else
                {
                    confirmorder.Text = "Confirm order";

                }

            }
        }

        protected void editDeliveryInfo_Click(object sender, EventArgs e)
        {

            diholder.Visible = true;
            confirmationholder.Visible = false;
        }

        protected void confirmorder_Click(object sender, EventArgs e)
        {
            // Create customerinformation
            CustomerInfo ci = new CustomerInfo();
            ci.AddData("company", txtInvCompany.Text);
            ci.AddData("firstname", txtInvFirstname.Text);
            ci.AddData("lastname", txtInvLastname.Text);
            ci.AddData("email", txtInvEmail.Text);
            ci.AddData("streetname", txtInvStreet.Text);
            ci.AddData("postalcode", txtInvPost.Text);
            ci.AddData("city", txtInvCity.Text);
            ci.AddData("country", ddlInvCountry.SelectedValue);
            ci.AddData("telephone", txtInvPhone.Text);

            //Delivery adress
            ci.AddData("delivery company", txtDelCompany.Text);
            ci.AddData("delivery firstname", txtDelFirstname.Text);
            ci.AddData("delivery lastname", txtDelLastname.Text);
            ci.AddData("delivery streetname", txtDelStreet.Text);
            ci.AddData("delivery postalcode", txtDelPost.Text);
            ci.AddData("delivery city", txtDelCity.Text);
            ci.AddData("delivery country", ddlDelCountry.SelectedValue);

            // Create order
            Order.DeleteUnconfirmedOrdersFromSession(Session.SessionID);
            Order o = Order.MakeNew(ci.ToXml(), Request.UserHostAddress, new PaymentMethods.CollectOnDelivery().Id, Page.Session.SessionID, txtInvEmail.Text);

            foreach (CartItem c in Library.GetCart.Items)
            {
                OrderLine l = new OrderLine();
                l.Quantity = c.Quantity;
                l.ProductName = c.ProductName;
                l.Price = c.Price;
                l.ProductId = c.ProductId;
                o.AddOrderLine(l);
            }

            // Add delivery fee product
            OrderLine p = new BusinessLogic.OrderLine();
            p.Price = (Store.GetDeliveryCostByCountry(ddlInvCountry.SelectedValue));
            p.Quantity = 1;
            p.ProductName = Store.LevName(ddlInvCountry.SelectedValue);
            p.ProductId = Store.LevID(ddlInvCountry.SelectedValue);
            o.AddOrderLine(p);

            //Set order status to "not confirmed"
            o.OrderStatus = Order.Status.NotConfirmed;

            if (rdbPayment.SelectedIndex == 0)
            {
                // Go to payment
                //Response.Redirect(Store.QuerySettingsFileOutput("/settings/quickpay/paymentformurl") +"?session=" + Session.SessionID);
                Response.Redirect(umbraco.library.NiceUrl(umbraco.presentation.nodeFactory.Node.GetCurrent().Id) + "/errorpage?orderid=" + o.OrderId + "&time=" + o.OrderTimeStamp);
            }
            else
            {
                DoOrderFinalisation(o);
                Library.ClearCart();
            }

            // Add the order to the logged in customer
            try
            {
                if (Member.IsLoggedOn())
                {
                    Member m = Member.GetCurrentMember();
                    m.getProperty("orders").Value += "," + o.OrderId;
                    m.XmlGenerate(new System.Xml.XmlDocument());
                }
            }
            catch
            {

            }

            // Say thankyou in a nice maner!
            lttConfirmationEmail.Text = txtInvEmail.Text;
            thankyou.Visible = true;

            diholder.Visible = false;
            confirmationholder.Visible = false;

        }
        public static void DoOrderFinalisation(Order o)
        {

            o.OrderStatus = Order.Status.Confirmed;

            try
            {
                // Create an pdf version of the order confirmation.
                // Pdf.OrderToPdf.generateOrderPdf(o.OrderId);

            }
            catch
            {

            }

            try
            {
                string senderemail = Store.QuerySettingsFileOutput("/settings/confirmationemail/senderemail");
                string shopemail = Store.QuerySettingsFileOutput("/settings/confirmationemail/shopemail");
                string subject = Store.QuerySettingsFileOutput("/settings/confirmationemail/subject");

                if (senderemail == "") senderemail = "nomail@configured.com";
                if (shopemail == "") shopemail = "nomail@configured.com";
                if (subject == "") subject = "no subject configured in the configfile";

                string email = new CustomerInfo(o.CustomerInformation).GetValue("email");

                Library.SendOrderConfirmationMail(o.OrderId, email, senderemail, subject);
                Library.SendOrderConfirmationMail(o.OrderId, shopemail, senderemail, subject);

            }
            catch
            {
            }
        }

        protected void rblDeliveryadress_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblDeliveryadress.SelectedIndex == 0)
            {
                pnlDelivery.Visible = true;
            }
            if (rblDeliveryadress.SelectedIndex == 1)
            {
                pnlDelivery.Visible = false;
            }
        }




    }
}